package com.fxw.mylibrary;

import android.app.Activity;
import android.app.Application;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Title:
 * @Description:
 * @Author: xianwen.fu
 * @Date: 2017/2/9 12:03
 */

public abstract class BaseAppContext extends Application {

    private static BaseAppContext instance;
    //存放activity栈
    private CopyOnWriteArrayList<Activity> mStack = new CopyOnWriteArrayList<Activity>();

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        init();
    }

    protected abstract void init();

    public static BaseAppContext getInstance() {
        return instance;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    /**
     * finish一个activity
     *
     * @param activity
     * @Description:
     */
    public void addActivity(Activity activity) {
        try {
            if (activity != null && !activity.isFinishing()) {
                mStack.add(activity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void finishActivity(Activity activity) {
        try {
            activity.finish();
            mStack.remove(activity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void finishActivity(Class<?> clazz) {
        try {
            for (Activity activity : mStack) {
                if (activity.getClass().getName().equals(clazz.getName())) {
                    activity.finish();
                    mStack.remove(activity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 结束所有activity
     *
     * @Description:
     */
    public void finishAllActivity() {
        try {
            for (Activity activity : mStack) {
                if (activity != null) {
                    activity.finish();
                }
            }
            mStack.clear();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 结束其它activity
     *
     * @param activity
     * @Description:
     */
    public void finishOthersActivity(Activity activity) {
        try {
            for (Activity a : mStack) {
                if (a != null && a != activity) {
                    a.finish();
                    mStack.remove(a);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否只存在一个activity实例
     *
     * @return
     */
    public boolean existActivityOne() {
        if (mStack.size() == 1)
            return true;
        else return false;
    }

    public Activity getLastActivity() {
        if (mStack.size() != 0)
            return mStack.get(mStack.size() - 1);
        else return null;
    }
}
